<template>
  <div class="pagination-list">
    <!-- 显示列表标题 -->
    <h2 v-if="title">{{ title }}</h2>
    <!-- 列表容器 -->
    <div class="list-container">
      <template v-if="paginatedData.length">
        <ul>
          <!-- 循环渲染当前页的数据 -->
          <div v-for="(item, index) in paginatedData" :key="index" style="width: 100%;">
              <!-- 使用插槽自定义列表项展示 -->
              <slot :item="item" :index="index">
                <!-- 默认展示对象字符串形式 -->
                {{ itemToString(item) }}
              </slot>
          </div>
        </ul>
      </template>
      <div v-else class="empty-message">暂无数据</div>
    </div>
    <!-- 分页组件 -->
    <div>
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :small="small" :disabled="disabled"
        :background="background" layout="prev, pager, next, jumper,  total" :total="total"
        @current-change="handleCurrentChange" @size-change="handleSizeChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 定义组件属性
const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  title: {
    type: String,
    default: '',
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  total: {
    type: Number,
    default: 0,
  },
  currentPage: {
    type: Number,
    default: 1,
  },
});

// 定义组件事件
const emit = defineEmits(['page-change', 'size-change']);

// 当前页码
const currentPage = ref(props.currentPage);
// 每页显示数量
const pageSize = ref(props.pageSize);
// 计算总数据量
const total = computed(() => {
  return props.total || props.data.length;
});

// 计算当前页要展示的数据
const paginatedData = computed(() => {
  const start = 0;
  const end = pageSize.value;
  console.log(props.data.slice(start, end));
  return props.data.slice(start, end);
});

// const data = paginatedData.value;
// console.log("data", data);

// 处理页码改变事件
const handleCurrentChange = (page) => {
  currentPage.value = page;
  emit('page-change', page);
};

// 处理每页显示数量改变事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  emit('size-change', size);
};

// 将对象转换为字符串
const itemToString = (item) => {
  if (typeof item === 'object' && item !== null) {
    return Object.entries(item)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ');
  }
  return String(item);
};
</script>

<style scoped>
.pagination-list {
  width: 100%;
}

.list-container {
  margin-bottom: 20px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 8px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.empty-message {
  text-align: center;
  color: #999;
  padding: 20px;
}

.pagination-controls {
  width: 100%;
}
</style>
